// 使用 Mock
var Mock = require('mockjs')
// mysql8.0需要执行下边的sql，否则nodejs不支持
// ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY '自己的密码';
var mysql = require('mysql');
// 定义连接池
const pool = mysql.createPool({
    host: "127.0.0.1", // 主机地址
    port: 3306,
    database: "ydl", // 数据库名字
    user: "root", // 连接数据库的用户名
    password: "600600", // 连接数据库密码
    connectionLimit: 30, // 连接池最大连接数
    multipleStatements: true // 允许执行多条sql语句
})


function insert(connection) {
    let content = '';
    for (var i = 0; i < 100; i++) {
        // 使用mock.js模拟数据
        var user = Mock.mock({
            userName: Mock.mock('@name(true)'),
            nickName: Mock.mock('@cname()'),
            email: Mock.mock('@email()'),
            sex: Math.random() > 0.5 ? '男' : '女',
            loginIp: Mock.mock('@ip()'),
            loginDate: Mock.mock('@datetime()'),
            password: Mock.mock('@word(5, 10)'),
            avatar: Mock.mock('@url()'),
            text: Mock.mock('@cparagraph(30)'),
        });

        // 每次存入1000条
        let insertData = '('
        for (key in user) {
            insertData += '\'' + user[key] + '\'' + ','
        }
        insertData = insertData.substring(0, insertData.length - 1) + ')';
        content += insertData + ',';
    }

    content = content.substring(0, content.length - 1);
    let sql = `insert into user (user_name,
        nick_name,email,sex,login_ip,login_date,password,avatar,text) values
        ${content}`;
    connection.query(sql);
    connection.release();
}
// 循环60000万次，总计能插入600万条
for (let i = 0; i < 60000; i++)
{

    pool.getConnection(function (err, connection) {
        // 代码
        insert(connection)
        console.log('第'+i+'条sql执行成功！')
    })
}
